﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using MySql.Data.MySqlClient;
using 文华财经数据解析.entity;
using 文华财经数据解析.utils.WHDataServer;

namespace 文华财经数据解析.utils
{
    internal class MyUtil
    {
        static string connectStr33 = "server=172.16.16.33;port=3306;database=info;user=root;password=dyqh@9882";

        static Dictionary<string, CodeType> codeTypeDic = new Dictionary<string, CodeType>();

        static Dictionary<string, Scode> whScodeDic = new Dictionary<string, Scode>();

        static Dictionary<string,Scode> wpScodeDic = new Dictionary<string, Scode>();


        static MyUtil()
        {
            
            string sql = "select futuexchtype,codetype,codeprefix,codetypename,multi,step,dayOrNight,isHy,type from codetype";
            codeTypeDic = new Dictionary<string, CodeType>();
            List<CodeType> codeTypes = DBUtil.ExecuteQuery<CodeType>(sql, connectStr33);
            for (int i = 0; i < codeTypes.Count; i++) 
            { 
                CodeType codeType = codeTypes[i];
                string pzdm = codeType.codeprefix;
                if (!codeTypeDic.ContainsKey(pzdm))
                {
                    codeTypeDic.Add(pzdm,codeType);
                }
            }


            //文华指数
            string sql2 = "select scodetype,scodename,business_name,wjj from scode_wh";
            whScodeDic = new Dictionary<string, Scode>();
            List<Scode> whScodeList = DBUtil.ExecuteQuery<Scode>(sql2,connectStr33);
            for (int i = 0; i < whScodeList.Count; i++)
            {
                Scode scode = whScodeList[i];
                string scodetype = scode.scodetype;
                if (!whScodeDic.ContainsKey(scodetype))
                {
                    whScodeDic.Add(scodetype, scode);
                }
            }


            //外盘指数
            string sql3 = "select scodetype,scodename,business_name,wjj from scode_wp";
            wpScodeDic = new Dictionary<string, Scode>();
            List<Scode> wpScodeList = DBUtil.ExecuteQuery<Scode>(sql3, connectStr33);
            for(int i = 0;i < wpScodeList.Count; i++)
            {
                Scode scode = wpScodeList[i];
                string scodetype = scode.scodetype;
                if (!wpScodeDic.ContainsKey(scodetype))
                {
                    wpScodeDic.Add(scodetype, scode); 
                }
            }


        }


        public static string getInfoWpMaxDate()
        {
            string sql = "SELECT max(date) FROM `info_wp`";
            string date = DBUtil.ExecuteQuery<string>(sql, connectStr33).FirstOrDefault();

            return date;
        }



        /// <summary>
        /// 获取起止日期之间的日期列表
        /// </summary>
        /// <param name="startDateStr"></param>
        /// <param name="endDateStr"></param>
        /// <returns></returns>
        public static List<string> GetDatesBetween(string startDateStr, string endDateStr)
        {
            var dates = new List<string>();

            // 解析输入的字符串为 DateTime
            DateTime startDate = DateTime.ParseExact(startDateStr, "yyyyMMdd", null);
            DateTime endDate = DateTime.ParseExact(endDateStr, "yyyyMMdd", null);

            // 生成起始日期到结束日期的所有日期
            for (var date = startDate; date <= endDate; date = date.AddDays(1))
            {
                dates.Add(date.ToString("yyyyMMdd"));
            }

            return dates;
        }


        ////落地品种的加权日K数据
        //public static void LoadWeightDayKLineData(string startDate, string endDate, WHServer whServer)
        //{
        //    //获取日期列表
        //    List<string> dateList = MyUtil.GetDatesBetween(startDate, endDate);

        //    string sql = "select scodetype,scodename,business_name,wjj from scode";
        //    List<Scode> scodes = DBUtil.ExecuteQuery<Scode>(sql,connectStr33);
        //    for (int i = 0; i < scodes.Count; i++)
        //    {
        //        Scode scode = scodes[i];
        //        string pzdm = scode.scodetype;
        //        string scodenameStr = scode.scodename;
        //        //int value = int.Parse(scodenameStr);
        //        //ushort scodename = ushort.Parse((int.Parse(scodenameStr)).ToString());
        //        string wjj = scode.wjj;
        //        List<KlineData> KlineDatas = whServer.GetKLineData(pzdm,wjj, scodenameStr, DateTime.Now);
        //        for (int j = 0; j < KlineDatas.Count; j++)
        //        {
        //            KlineData KlineData = KlineDatas[j];
        //            string date = KlineData.date;
        //            if (dateList.Contains(date))
        //            {
        //                InsertDayKLineData(KlineData);
        //            }
        //        }
        //    }
        //}


        //插入日K数据库
        public static void InsertDayKLineData(KlineData data,string table, string comparisonTime)
        {
            //string table = "info_test";
            string date = data.date;
            string time = data.time;
            //string comparisonTime = "20:30:00";
            bool isLessThan = DateTime.ParseExact(time, "HH:mm:ss", CultureInfo.InvariantCulture) <= DateTime.ParseExact(comparisonTime, "HH:mm:ss", CultureInfo.InvariantCulture);
            if (isLessThan==false)
            {
                return;
            }

            string pzdm = data.pzdm;

            string business_name = null;
            string code = null;
            double open = Math.Round(data.open, 4);
            double close = Math.Round(data.close, 4);
            double high = Math.Round(data.high, 4);
            double low = Math.Round(data.low, 4);
            double cjl = data.cjl;
            double ccl = data.ccl;
            double avg = Math.Round(data.avg, 4);
            string allTime = data.allTime;


            if (whScodeDic.ContainsKey(pzdm) && table == "info_wh")
            {
                business_name = whScodeDic[pzdm].business_name;
                code = whScodeDic[pzdm].scodename;
            }else if(codeTypeDic.ContainsKey(pzdm) && table == "info")
            {
                CodeType codeType = codeTypeDic[pzdm];
                business_name = codeType.futuexchtype.Substring(0, 2);
                code = data.code;
            }else if (wpScodeDic.ContainsKey(pzdm) && table == "info_wp")
            {
                business_name = wpScodeDic[pzdm].business_name;
                code = wpScodeDic[pzdm].scodename;
            }



            //CodeType codeType = codeTypeDic[pzdm];
            //string business_name = codeType.futuexchtype.Substring(0,2);
            //string code = data.code;
            //double open = Math.Round(data.open, 4);
            //double close = Math.Round(data.close, 4);
            //double high = Math.Round(data.high, 4);
            //double low = Math.Round(data.low, 4);
            //double cjl = data.cjl;
            //double ccl = data.ccl;
            //double avg = Math.Round(data.avg, 4);
            //string allTime = data.allTime;


            int count = 0;
            // 查询是否存在相同记录
            string query = $"SELECT COUNT(*) FROM {table} WHERE date = '{date}' AND name = '{pzdm}'";

            using (var connection = new MySqlConnection(connectStr33))
            {
                connection.Open();
                using (var cmd = new MySqlCommand(query, connection))
                {
                    count = Convert.ToInt32(cmd.ExecuteScalar());
                }
            }

            if (count > 0)
            {
                // 更新操作
                string updateSql = $"UPDATE {table} SET " +
                    $"date = '{date}', " +
                    $"business_name = '{business_name}', " +
                    $"pzdm = '{pzdm}', " +
                    $"name = '{pzdm}', " +
                    $"opening = {open}, " +
                    $"highest_price = {high}, " +
                    $"lowest_price = {low}, " +
                    $"today_close = {close}, " +
                    $"clearing = {avg}, " +
                    $"turnover_hand = {cjl}, " +
                    $"empty_plate = {ccl} " +
                    $"WHERE date = '{date}' AND name = '{pzdm}'";

                DBUtil.ExecuteNonQuery(updateSql, connectStr33);
                Console.WriteLine("更新数据 " + date + " " + pzdm + " " + allTime);
            }
            else
            {
                // 插入操作
                string insertSql = $"INSERT INTO {table} (date, pzdm,business_name, name, opening, highest_price, lowest_price, " +
                    $"today_close, turnover_hand, empty_plate ) VALUES (" +
                    $"'{date}', '{pzdm}', '{business_name}', '{pzdm}', {open}, {high}, {low}," +
                    $" {close}, {cjl}, {ccl})";

                DBUtil.ExecuteNonQuery(insertSql, connectStr33);
                Console.WriteLine("插入数据 " + date + " " + pzdm + " " + allTime);
            }


        }







    }
}
